package cn.lovecyy.mockjson.core.domain;

import cn.lovecyy.mockjson.core.funcs.FuncCall;

import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TypeConfig
 *
 * @author Yakir
 */
@Data
public class TypeConfig {

	// 字段key
	private String key;

	// 字段值 type|param|format
	private String value;

	// 切分后的类型
	public String type;

	// 参数
	public String param;

	// 格式
	public String format;

	// 上下文
	public Map<String, Object> context = new HashMap<>();

	// 新增：主参数
	private String mainParam;

	// 新增：函数链
	private java.util.List<FuncCall> functionChain = new ArrayList<>();

	public static TypeConfig parse(String key, String value) {
		String[] arr = value.split("\\|", -1);
		TypeConfig tc = new TypeConfig();
		tc.key = key;
		tc.value = value;
		tc.type = arr.length > 0 ? arr[0] : "";
		tc.param = arr.length > 1 ? arr[1] : "";
		tc.format = arr.length > 2 ? arr[2] : "";
		// 新增：解析param为主参数+函数链
		parseParamAndFunctions(tc);
		return tc;
	}

	// 解析param为主参数+函数链
	private static void parseParamAndFunctions(TypeConfig tc) {
		String param = tc.param;
		if (param == null || param.isEmpty()) {
			tc.mainParam = "";
			return;
		}
		String trimmed = param.trim();
		int len = trimmed.length();
		boolean inQuote = false;
		int splitIdx = -1;
		for (int i = 0; i < len; i++) {
			char c = trimmed.charAt(i);
			if (c == '\'') {
				inQuote = !inQuote;
			}
			else if (c == ':' && !inQuote) {
				splitIdx = i;
				break;
			}
		}
		if (splitIdx == -1) {
			// 没有函数链，直接去除主参数首尾单引号
			tc.mainParam = trimmed.replaceAll("^'|'$", "");
			return;
		}
		// 主参数
		String main = trimmed.substring(0, splitIdx).trim();
		tc.mainParam = main.replaceAll("^'|'$", "");
		// 函数链
		String funcs = trimmed.substring(splitIdx + 1);
		// 以冒号分割函数链（同样要考虑引号包裹）
		List<String> funcParts = smartSplitFuncChain(funcs);
		for (String func : funcParts) {
			int idx = func.indexOf('(');
			if (idx > 0 && func.endsWith(")")) {
				String name = func.substring(0, idx);
				String argStr = func.substring(idx + 1, func.length() - 1);
				List<String> args = smartSplitArgs(argStr);
				tc.getFunctionChain().add(new FuncCall(name, args));
			}
			else {
				tc.getFunctionChain().add(new FuncCall(func.trim(), new ArrayList<>()));
			}
		}
	}

	public static List<String> smartSplitFuncChain(String funcs) {
		List<String> funcParts = new ArrayList<>();
		StringBuilder sb = new StringBuilder();
		boolean inQuote = false;
		int parenLevel = 0;
		for (int i = 0; i < funcs.length(); i++) {
			char c = funcs.charAt(i);
			if (c == '\'') {
				inQuote = !inQuote;
			}
			else if (c == '(' && !inQuote) {
				parenLevel++;
			}
			else if (c == ')' && !inQuote) {
				parenLevel--;
			}
			else if (c == ':' && !inQuote && parenLevel == 0) {
				funcParts.add(sb.toString());
				sb.setLength(0);
				continue;
			}
			sb.append(c);
		}
		if (sb.length() > 0) {
			funcParts.add(sb.toString());
		}
		return funcParts;
	}

	public static List<String> smartSplitArgs(String argStr) {
		List<String> args = new ArrayList<>();
		if (argStr == null || argStr.isEmpty())
			return args;
		StringBuilder sb = new StringBuilder();
		boolean inQuote = false;
		for (int i = 0; i < argStr.length(); i++) {
			char c = argStr.charAt(i);
			if (c == '\'') {
				inQuote = !inQuote;
			}
			else if (c == ',' && !inQuote) {
				// 去除首尾单引号

				args.add(sb.toString().trim().replaceAll("^'|'$", "")); // 去除首尾单引号

				sb.setLength(0);
			}
			else {
				sb.append(c);
			}
		}
		if (sb.length() > 0) {
			args.add(sb.toString().trim().replaceAll("^'|'$", "")); // 去除首尾单引号
		}
		return args;
	}

}
